import re
import os
from django.shortcuts import render,redirect,HttpResponse
from user_system import models
from utils.auth_manog import auth_manog_done
from k8sMp.settings import BASE_DIR
from django.http import JsonResponse
from k8sMp.settings import logger
from django.db.models import Q

@auth_manog_done
def project_list(request):
    """项目列表"""
    if request.method == "GET":
        project_list = models.Project.objects.all()
        return render(request,'super_cmdb/project_list.html',{"project_list":project_list})
    if request.method == "POST":
        project_filter = request.POST.get("project_filter")
        project_filter = project_filter.strip()
        project_list = models.Project.objects.filter(
            Q(name__contains=project_filter) |
            Q(cloud_project_id__contains=project_filter) |
            Q(cloud_project_id2__contains=project_filter) |
            Q(cloud_project_id3__contains=project_filter) |
            Q(cloud_account_id1__contains=project_filter) |
            Q(cloud_account_id2__contains=project_filter) |
            Q(cloud_account_id3__contains=project_filter) |
            Q(describe__contains=project_filter)
        ).all()
        return render(request, 'super_cmdb/project_list.html', {"project_list": project_list,"project_filter":project_filter})


@auth_manog_done
def project_add(request):
    """项目添加"""
    if request.method == "GET":
        cloud_account_list = models.Cloud_Account.objects.all()
        return render(request,'super_cmdb/project_add.html',{"cloud_account_list":cloud_account_list})
    if request.method == "POST":
        name = request.POST.get("name")
        cloud_project_id = request.POST.get("cloud_project_id")
        cloud_account_id1 = request.POST.get("cloud_account_id1")      #cloud_account_id 应该关联云账号的自增id的，前端应该传自增id过来，万一云账号修改了又要重新关联一遍了，暂时问题不大，云账号也是唯一的
        if cloud_project_id == "None":
            cloud_project_id = None
            cloud_account_id1 = None
        cloud_project_id2 = request.POST.get("cloud_project_id2")
        cloud_account_id2 = request.POST.get("cloud_account_id2")
        if cloud_project_id2 == "None":
            cloud_project_id2 = None
            cloud_account_id2 = None
        cloud_project_id3 = request.POST.get("cloud_project_id3")
        cloud_account_id3 = request.POST.get("cloud_account_id3")
        if cloud_project_id3 == "None":
            cloud_project_id3 = None
            cloud_account_id3 = None
        name_en = request.POST.get("name_en")
        describe = request.POST.get("describe")
        project_path = os.path.join(BASE_DIR,"project_package",name_en)
        try:
            if not models.Project.objects.filter(name=name).first():
                models.Project.objects.create(
                    name=name,
                    cloud_project_id=cloud_project_id,
                    cloud_project_id2=cloud_project_id2,
                    cloud_project_id3=cloud_project_id3,
                    name_en=name_en,
                    describe=describe,
                    cloud_account_id1=cloud_account_id1,
                    cloud_account_id2=cloud_account_id2,
                    cloud_account_id3=cloud_account_id3
                )
                if not os.path.exists(project_path):
                    os.makedirs(project_path)
                message = {"code": 0,"msg": "项目添加成功，ok"}
                return JsonResponse(message)
            else:
                message = {"code": 1, "msg": "项目已存在，不可重复添加"}
                return JsonResponse(message)
        except Exception as e:
            message = {"code": 1, "msg": "项目添加失败，Error: %s"%e}
            return JsonResponse(message)

@auth_manog_done
def project_edit(request,project_id):
    """项目编辑"""
    if request.method == "GET":
        project_info = models.Project.objects.filter(id=project_id).first()
        cloud_account_list = models.Cloud_Account.objects.all()
        return render(request,"super_cmdb/project_edit.html",{"project_info":project_info,"cloud_account_list":cloud_account_list})
    if request.method == "POST":
        name = request.POST.get("name")
        cloud_project_id = request.POST.get("cloud_project_id")
        cloud_account_id1 = request.POST.get("cloud_account_id1")
        if cloud_project_id == "None":
            cloud_project_id = None
            cloud_account_id1 = None
        cloud_project_id2 = request.POST.get("cloud_project_id2")
        cloud_account_id2 = request.POST.get("cloud_account_id2")
        if cloud_project_id2 == "None":
            cloud_project_id2 = None
            cloud_account_id2 = None
        cloud_project_id3 = request.POST.get("cloud_project_id3")
        cloud_account_id3 = request.POST.get("cloud_account_id3")
        if cloud_project_id3 == "None":
            cloud_project_id3 = None
            cloud_account_id3 = None
        name_en = request.POST.get("name_en")
        describe = request.POST.get("describe")
        try:
            obj = models.Project.objects.get(id=project_id)
            obj.name = name
            obj.cloud_project_id = cloud_project_id
            obj.cloud_project_id2 = cloud_project_id2
            obj.cloud_project_id3 = cloud_project_id3
            obj.cloud_account_id1 = cloud_account_id1
            obj.cloud_account_id2 = cloud_account_id2
            obj.cloud_account_id3 = cloud_account_id3
            obj.name_en = name_en
            obj.describe = describe
            obj.save()
            return HttpResponse('ok')
        except Exception as e:
            logger.error(e)
            logger.error('异常文件：%s ,异常行号：%s' % (e.__traceback__.tb_frame.f_globals['__file__'], e.__traceback__.tb_lineno))
            return HttpResponse("faild")

@auth_manog_done
def project_del(request):
    """项目删除"""
    if request.method == "POST":
        project_id = request.POST.get("project_id")   #前端传过来的全是字符串
        nums = re.findall(r'\d+', project_id)      #匹配user_id组成数组
        if isinstance(nums,list):    #判断user_id是不是一个list
            for id in nums:
                #id = int(id)
                name = models.Project.objects.filter(id=id).first().name
                models.Project.objects.filter(id=id).delete()
                log_success = "删除用户【%s】成功" % name
                logger.info(log_success)
        return redirect("/super_cmdb/project_list/")

@auth_manog_done
def permission_set(request):
    """配置权限"""
    if request.method == "GET":
        user_list = models.User.objects.all()
        project_list = models.Project.objects.all().order_by("-name")
        return render(request,"super_cmdb/permission_set.html",{"user_list":user_list,"project_list":project_list})
    if request.method == "POST":
        status = request.POST.get("status")
        user_id = request.POST.get("user_id")
        project_id = request.POST.get("project_id")
        try:
            user_obj = models.User.objects.get(id=user_id)
            project_obj = models.Project.objects.get(id=project_id)
            host_obj = project_obj.serverhost_set.all()
            if status == "setting":
                ###多对多操作：增加数据   开始### 用户与项目是多对多关联的，当配置时，把用户与项目关联
                user_obj.project.add(project_obj)
                #用户关联属于项目id的所有机器
                user_obj.serverhost_set.add(*host_obj)    #一个用户关联多台机器
                logger.info("用户id:%s关联属于项目id：%s的所有机器成功"%(user_id,project_id))
                ###多对多操作：增加数据   结束###
            else:
                ###多对多操作：删除数据   开始### 用户与项目删除关联
                user_obj.project.remove(project_obj)
                # 删除用户关联属于项目id的所有机器
                user_obj.serverhost_set.remove(*host_obj)
                logger.info("删除用户id:%s关联属于项目id：%s的所有机器成功"%(user_id,project_id))
                ###多对多操作：增加数据   结束###
            return HttpResponse("ok")
        except Exception as e:
            logger.error(e)
            return HttpResponse("faild")
